package pers.brozen.anka.service.ac;

import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import pers.brozen.anka.support.web.response.ErrorCodes;
import pers.brozen.anka.support.web.response.ResponseException;
import pers.brozen.anka.support.wechat.WeChatException;
import pers.brozen.anka.support.wechat.WeChatMiniProgramAPI;
import pers.brozen.anka.support.wechat.response.MiniProgramCode2SessionResult;

/**
 * @author Brozen
 * @since 2024-05-28
 */
@Slf4j
@Component
public class WechatMiniProgramAC {

    @Resource
    private WeChatMiniProgramAPI miniProgramAPI;


    public MiniProgramCode2SessionResult requestWeChatSession(String jsCode) {
        try {
            MiniProgramCode2SessionResult session = miniProgramAPI.getSession(jsCode);
            if (StringUtils.isBlank(session.getOpenid())) {
                log.error("微信未返回 openId");
                throw new ResponseException(ErrorCodes.WECHAT_API_ERROR);
            }

            return session;
        } catch (WeChatException e) {
            log.error("微信认证异常", e);
            throw new ResponseException(ErrorCodes.WECHAT_API_ERROR);
        }
    }

}
